// 会员卡管理 - 会员卡列表接口
const Router = require("koa-router");
const router = new Router();

// 会员卡数据结构 - 使用静态数据而不是Mock.js
const memberCardList = [
  {
    id: 10001,
    memberCardNumber: "MC10001",
    cardType: "普通卡",
    issueDate: "2024-01-15",
    holderName: "张三",
    holderPhone: "13800138000",
    cardBalance: 500.5,
    cardStatus: 1,
    transactionRecords: [
      {
        transactionDate: "2024-02-18",
        transactionAmount: 50.0,
        transactionType: "充电扣款",
      },
    ],
    validUntil: "2024-12-31",
    rechargeTotal: 1000.0,
    consumptionTotal: 499.5,
  },
  {
    id: 10002,
    memberCardNumber: "MC10002",
    cardType: "VIP卡",
    issueDate: "2024-02-20",
    holderName: "李四",
    holderPhone: "13900139000",
    cardBalance: 1200.75,
    cardStatus: 1,
    transactionRecords: [
      {
        transactionDate: "2024-04-08",
        transactionAmount: 100.0,
        transactionType: "服务费扣款",
      },
      {
        transactionDate: "2024-05-15",
        transactionAmount: 50.0,
        transactionType: "充电扣款",
      },
    ],
    validUntil: "2024-12-31",
    rechargeTotal: 1500.0,
    consumptionTotal: 299.25,
  },
  {
    id: 10003,
    memberCardNumber: "MC10003",
    cardType: "季卡",
    issueDate: "2024-03-10",
    holderName: "王五",
    holderPhone: "13700137000",
    cardBalance: 800.0,
    cardStatus: 2,
    transactionRecords: [
      {
        transactionDate: "2024-10-03",
        transactionAmount: 200.0,
        transactionType: "停车费扣款",
      },
    ],
    validUntil: "2024-06-10",
    rechargeTotal: 1000.0,
    consumptionTotal: 200.0,
  },
  {
    id: 10004,
    memberCardNumber: "MC10004",
    cardType: "普通卡",
    issueDate: "2024-04-05",
    holderName: "赵六",
    holderPhone: "13600136000",
    cardBalance: 300.25,
    cardStatus: 1,
    transactionRecords: [
      {
        transactionDate: "2024-10-15",
        transactionAmount: 50.0,
        transactionType: "其他",
      },
    ],
    validUntil: "2024-12-31",
    rechargeTotal: 500.0,
    consumptionTotal: 199.75,
  },
  {
    id: 10005,
    memberCardNumber: "MC10005",
    cardType: "金卡",
    issueDate: "2024-05-12",
    holderName: "钱七",
    holderPhone: "13500135000",
    cardBalance: 2000.0, // 余额
    cardStatus: 1, // 1-正常, 2-冻结, 3-已过期
    // 交易记录
    transactionRecords: [
      {
        transactionDate: "2024-11-20",
        transactionAmount: 300.0,
        transactionType: "会员充值",
      },
    ],
    validUntil: "2024-12-31", // 有效期
    rechargeTotal: 2500.0, // 总充值金额
    consumptionTotal: 500.0, // 总消费金额
  },
];

// 创建数据备份（用于重置）
const originalMemberCardList = JSON.parse(JSON.stringify(memberCardList));

/**
 * 会员卡列表接口
 * 路径：POST /membercard/memberList
 *
 * 请求参数：
 * {
 *   page: 1,            // 分页参数
 *   pageSize: 10,       // 分页大小
 *   no: "123",          // 会员卡号（可选）
 *   tel: "13800138000", // 手机号（可选）
 *   name: "张三",       // 姓名（可选）
 *   cardType: "VIP卡",  // 卡类型（可选）
 *   cardStatus: 1       // 卡状态（可选）
 * }
 */
router.post("/membercard/memberList", (ctx) => {
  try {
    // 解析请求参数
    const requestBody = ctx.request.body;
    const {
      page = 1,
      pageSize = 10,
      no,
      tel,
      name,
      cardType,
      cardStatus,
    } = requestBody;

    console.log("会员卡列表接口收到参数:", requestBody);

    // 筛选数据
    let filteredData = [...memberCardList];

    // 按会员卡号筛选
    if (no) {
      filteredData = filteredData.filter((item) =>
        item.memberCardNumber.includes(no)
      );
    }

    // 按手机号筛选
    if (tel) {
      filteredData = filteredData.filter((item) =>
        item.holderPhone.includes(tel)
      );
    }

    // 按姓名筛选
    if (name) {
      filteredData = filteredData.filter((item) =>
        item.holderName.includes(name)
      );
    }

    // 按卡类型筛选
    if (cardType) {
      filteredData = filteredData.filter((item) => item.cardType === cardType);
    }

    // 按卡状态筛选
    if (cardStatus) {
      filteredData = filteredData.filter(
        (item) => item.cardStatus == cardStatus
      );
    }

    // 计算分页
    const pageNum = parseInt(page);
    const size = parseInt(pageSize);
    const startIndex = (pageNum - 1) * size;
    const endIndex = startIndex + size;
    const paginatedData = filteredData.slice(startIndex, endIndex);

    // 返回响应 - 符合您的组件期望的数据结构
    ctx.body = {
      code: 200,
      message: "操作成功",
      data: {
        list: paginatedData,
        total: filteredData.length,
      },
    };
  } catch (error) {
    console.error("会员卡列表接口出错:", error);
    ctx.body = {
      code: 500,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

/**
 * 会员卡统计接口
 * 路径：GET /membercard/memberStats
 *
 * 说明：此接口返回会员卡数据的统计信息
 */
router.get("/membercard/memberStats", (ctx) => {
  try {
    console.log("会员卡统计接口被调用");

    // 按卡类型统计
    const cardTypeStats = {};
    memberCardList.forEach((item) => {
      if (!cardTypeStats[item.cardType]) {
        cardTypeStats[item.cardType] = 0;
      }
      cardTypeStats[item.cardType]++;
    });

    // 按卡状态统计
    const cardStatusStats = {
      正常: memberCardList.filter((item) => item.cardStatus === 1).length,
      冻结: memberCardList.filter((item) => item.cardStatus === 2).length,
      已过期: memberCardList.filter((item) => item.cardStatus === 3).length,
    };

    // 计算总余额和平均余额
    const totalBalance = memberCardList.reduce(
      (sum, item) => sum + parseFloat(item.cardBalance),
      0
    );
    const avgBalance = totalBalance / memberCardList.length;

    // 计算总充值金额和总消费金额
    const totalRecharge = memberCardList.reduce(
      (sum, item) => sum + parseFloat(item.rechargeTotal),
      0
    );
    const totalConsumption = memberCardList.reduce(
      (sum, item) => sum + parseFloat(item.consumptionTotal),
      0
    );

    // 返回统计信息
    ctx.body = {
      code: 200,
      message: "操作成功",
      data: {
        total: memberCardList.length,
        cardTypeStats,
        cardStatusStats,
        totalBalance: totalBalance.toFixed(2),
        avgBalance: avgBalance.toFixed(2),
        totalRecharge: totalRecharge.toFixed(2),
        totalConsumption: totalConsumption.toFixed(2),
      },
    };
  } catch (error) {
    console.error("会员卡统计接口出错:", error);
    ctx.body = {
      code: 500,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

// 导出路由
module.exports = router;
